package com.yunfeng.supercall.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Formatter.BigDecimalLayoutForm;

import org.json.JSONException;
import org.json.JSONObject;

import u.aly.di;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.text.Html;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lin.activity.PersonalDetailCardActivity;
import com.lin.utils.Parameters;
import com.lin.utils.Utils;
import com.ly.quickdev.library.adapter.ListBaseAdapter;
import com.ly.quickdev.library.utils.JsonUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.PinterestCircleBitmapDisplayer;
import com.yunfeng.supercall.R;
import com.yunfeng.supercall.activity.BaseActivity;
import com.yunfeng.supercall.activity.ChatActivity;
import com.yunfeng.supercall.activity.FriendsDetailActivity;
import com.yunfeng.supercall.activity.OutCallActivity;
import com.yunfeng.supercall.bean.Constants;
import com.yunfeng.supercall.bean.ContactsBaseBean;
import com.yunfeng.supercall.bean.PhoneContactsBean;
import com.yunfeng.supercall.bean.RecentCallsBean;
import com.yunfeng.supercall.bean.SuperFriendsBean;
import com.yunfeng.supercall.bean.UserBean;
import com.yunfeng.supercall.fragment.DialPadFragment;
import com.yunfeng.supercall.httputils.HttpClient;
import com.yunfeng.supercall.httputils.MyAjaxCallBack;
import com.yunfeng.supercall.manager.ManagerFactory;
import com.yunfeng.supercall.manager.SuperFriendsManager;

public class ContactsDialPadAdapter<T extends SuperFriendsBean> extends
		ListBaseAdapter<T> {
	SimpleDateFormat mSimpleDateFormat;
	SimpleDateFormat mSimpleDateFormat1;
	private UserBean mUser;
	SuperFriendsManager mSuperFriendsManager;
	private List<SuperFriendsBean> mFriends;
	Context context;
	DisplayImageOptions options;
	public ContactsDialPadAdapter(Context context, List<T> list) {
		super(context, list);
		options = new DisplayImageOptions.Builder()
		.displayer(new PinterestCircleBitmapDisplayer(context.getResources().getDimensionPixelOffset(R.dimen.corners_avatar)))
		.showImageOnFail(R.drawable.default_avatar)
		.showImageOnLoading(R.drawable.default_avatar)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.bitmapConfig(Bitmap.Config.RGB_565)
		.build();

		this.context = context;
		mSimpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		mSimpleDateFormat1 = new SimpleDateFormat("yyyy/MM/dd HH:mm");
		mUser = BaseActivity.getUser(context);
		mSuperFriendsManager = (SuperFriendsManager) ManagerFactory
				.createManager(SuperFriendsBean.class);
		mFriends = mSuperFriendsManager.getList();
	}

	@Override
	public int getItemViewType(int position) {
		// TODO Auto-generated method stub
		SuperFriendsBean friends = getItem(position);
		if (friends instanceof RecentCallsBean) {
			return 1;
		}
		return 0;
	}

	@Override
	public int getViewTypeCount() {
		// TODO Auto-generated method stub
		return 2;
	}

	private String mReplace = "";

	@Override
	public View initView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		final int type = getItemViewType(position);
		if (convertView == null) {
			if (type == 0) {
				convertView = getInflater().inflate(
						R.layout.list_item_contacts_dialpad, null);
			}
			if (type == 1) {
				convertView = getInflater().inflate(
						R.layout.list_item_recent_call, null);
			}
		}
		final SuperFriendsBean base = getItem(position);
		ContactsBaseBean.setupSingleLineContactsView(convertView, base);
		TextView number = ViewHolder.get(convertView, R.id.number);
		ImageView imageView = ViewHolder.get(convertView, R.id.iv);
		ImageLoader.getInstance().displayImage(Parameters.SERVER_PIC_URL + base.getPhoto(), imageView, options);
		if (!base.isContactsFromPhone() || base instanceof RecentCallsBean) {
			number.setText(replaceTextColor(base.getSuid(), mReplace, base));
		} else {
			number.setText(replaceTextColor(base.getPhone(), mReplace));
		}
		
		// append(number, base);
		if (type == 0) {
			final ImageView icon = ViewHolder.get(convertView, R.id.is_super);
			
			final LinearLayout mLinearLayout = ViewHolder.get(convertView, R.id.linearlayout);
			final FrameLayout mFrameLayout = ViewHolder.get(convertView, R.id.framelayout);
			
			if (base instanceof PhoneContactsBean) {
				PhoneContactsBean contacts = (PhoneContactsBean) base;
				Boolean b = DialPadFragment.IS_SUPER.get(contacts.getPhone());

				icon.setVisibility((b != null && b == true) ? View.VISIBLE
						: View.INVISIBLE);
				icon.setImageResource(R.drawable.ic_is_super_number);
				icon.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						startActivity(new Intent(getContext(),
								PersonalDetailCardActivity.class).putExtra(
								Constants.KEY_DATA, base));
					}
				});
			
				mFrameLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						
						startActivity(new Intent(getContext(),
								PersonalDetailCardActivity.class).putExtra(
								Constants.KEY_DATA, base));
						
					}
				});
				
				mLinearLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						if(((PhoneContactsBean) base).isSuperNum()) {
						startActivity(new Intent(getContext(),
								OutCallActivity.class).putExtra(Constants.KEY_DATA,
										base));
						} else {
							Utils.dial(base.getPhone(), context);
						}
						
					}
				});
			} else {
				icon.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final SuperFriendsBean friends = mSuperFriendsManager
								.findSuperFriendsByPhone(base.getPhone());
						if (friends != null) {
							startActivity(new Intent(getContext(),
									PersonalDetailCardActivity.class).putExtra(
									Constants.KEY_DATA, friends));
						} else {
							searchFriends(base.getPhone());
						}
					}
				});
				
				mFrameLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						
						startActivity(new Intent(getContext(),
								PersonalDetailCardActivity.class).putExtra(
								Constants.KEY_DATA, base));
						
					}
				});
				
				mLinearLayout.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						final SuperFriendsBean friends = mSuperFriendsManager
								.findSuperFriendsByPhone(base.getPhone());
						startActivity(new Intent(getContext(),
								OutCallActivity.class).putExtra(Constants.KEY_DATA,
										friends));
						
					}
				});
			}
		} else {
			
			final LinearLayout mLinearLayout = ViewHolder.get(convertView, R.id.linearlayout);
			
			final ImageView icon = ViewHolder.get(convertView, R.id.is_super);
			final RecentCallsBean call = (RecentCallsBean) base;
			number.setText(call.getSuperNumber());
			if (mFriends == null) {
				icon.setVisibility(View.INVISIBLE);
			} else {

				final SuperFriendsBean friends = mSuperFriendsManager
						.findSuperFriendsByPhone(call.getPhone());
					// icon.setVisibility(View.VISIBLE);
					icon.setImageResource(R.drawable.ic_arrow_right);
			}
			final FrameLayout mFrameLayout = ViewHolder.get(convertView, R.id.framelayout);
			mFrameLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					
					startActivity(new Intent(getContext(),
							PersonalDetailCardActivity.class).putExtra(
							Constants.KEY_DATA, base));
					
				}
			});
			icon.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final SuperFriendsBean friends = mSuperFriendsManager
							.findSuperFriendsByPhone(call.getPhone());
					if (friends != null) {
						startActivity(new Intent(getContext(),
								PersonalDetailCardActivity.class).putExtra(
								Constants.KEY_DATA, friends));
					} else {
						searchFriends(base.getPhone());
					}
				}
			});
			
			mLinearLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					final SuperFriendsBean friends = mSuperFriendsManager
							.findSuperFriendsByPhone(base.getPhone());
					startActivity(new Intent(getContext(),
							OutCallActivity.class).putExtra(Constants.KEY_DATA,
									friends));
					
				}
			});
			final TextView time = ViewHolder.get(convertView, R.id.time);
			RecentCallsBean calls = (RecentCallsBean) base;
			long date = 0;
			try {
				date = mSimpleDateFormat1.parse(calls.getCalltime()).getTime();
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			// long date = new cale
			time.setText(generateTime(date));
			final ImageView icon1 = ViewHolder.get(convertView, R.id.icon);
			int callType = 0;
			if (calls.getUser1() == mUser.getUserid()) {
				callType = RecentCallsBean.TYPE_OUT_CALL;
			} else {
				callType = RecentCallsBean.TYPE_IN_CALL;
			}
			if (calls.getState() == 0) {
				if (calls.getUser1() == mUser.getUserid()) {
					callType = RecentCallsBean.TYPE_MISSED_CALL;
				} else {
					callType = RecentCallsBean.TYPE_MISSED_CALL_OTHER;
				}

			}
			TextView callnum = ViewHolder.get(convertView, R.id.call_num);
			int num = call.getCallnum();
			if (num == 1) {
				callnum.setText("");
			} else {
				callnum.setText("(" + num + ")");
			}
			switch (callType) {
			case RecentCallsBean.TYPE_IN_CALL:
				icon1.setImageResource(R.drawable.ic_call_in);
				callnum.setTextColor(Color.rgb(23, 202, 44));
				break;
			case RecentCallsBean.TYPE_OUT_CALL:
				icon1.setImageResource(R.drawable.ic_call_out);
				callnum.setTextColor(Color.rgb(23, 202, 44));
				break;
			case RecentCallsBean.TYPE_MISSED_CALL:
				icon1.setImageResource(R.drawable.ic_missed_call_other);
				callnum.setTextColor(Color.rgb(236, 46, 14));
				break;
			case RecentCallsBean.TYPE_MISSED_CALL_OTHER:
				icon1.setImageResource(R.drawable.ic_call_missed);
				callnum.setTextColor(Color.rgb(236, 46, 14));
				break;
			}
		}
		return convertView;
	}

	private void searchFriends(String phone) {
		HttpClient mHttpClient = new HttpClient();
		JSONObject json = BaseActivity.getBaseParams(getContext());
		try {
			json.put("i_key", phone);
			json.put("i_type", 0);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		mHttpClient.post(Constants.FUNCTION_SEARCH_USER, json,
				new MyAjaxCallBack() {

					@Override
					public void onReceiveData(String data, String msg) {
						// TODO Auto-generated method stub
						try {
							SuperFriendsBean mSuperFriends = JsonUtils.parse(
									data.substring(1, data.length() - 1),
									SuperFriendsBean.class);
							if (mSuperFriends != null
									&& mSuperFriends.getVo_id() != null) {
								startActivity(new Intent(getContext(),
										PersonalDetailCardActivity.class).putExtra(
										Constants.KEY_DATA, mSuperFriends));
							} else {
							}
						} catch (Exception e) {
							// TODO Auto-generated catch block
						}
					}

					@Override
					public void onReceiveError(String msg, String errorCode) {
						// TODO Auto-generated method stub
					}
				});
	}

	public String generateTime(long date) {

		Date date2 = new Date(date);
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(date2);
		Calendar now = Calendar.getInstance();
		int count = now.get(Calendar.DAY_OF_YEAR)
				- calendar.get(Calendar.DAY_OF_YEAR);
		if (count == 1) {
			return "昨天 " + calendar.get(Calendar.HOUR_OF_DAY) + ":"
					+ calendar.get(Calendar.MINUTE);
		} else if(count == 2) {
			return "前天 " + calendar.get(Calendar.HOUR_OF_DAY) + ":"
					+ calendar.get(Calendar.MINUTE);
		} else if (count == 0) {
			int minu = calendar.get(Calendar.MINUTE);
			return calendar.get(Calendar.HOUR_OF_DAY) + ":"
			+ (minu < 10 ? "0" : "") + minu;
		}
		int minu = calendar.get(Calendar.MINUTE);
		return calendar.get(Calendar.MONTH) + "月" + calendar.get(Calendar.DAY_OF_MONTH) + "日 ";

	}

	public void setReplaceText(String text) {
		mReplace = text;
	}

	public static void append(TextView tv, ContactsBaseBean base) {
		if (base.getType() == ContactsBaseBean.TYPE_PERSONAL) {
			tv.append(ContactsBaseBean.replaceTextColor("8", "8", ContactsBaseBean.RED));
		} else {
			tv.append(
					ContactsBaseBean.replaceTextColor("0", "0", ContactsBaseBean.RED),
					0, 0);
		}
	}

	public static CharSequence replaceTextColor(String text, String replace,
			ContactsBaseBean base) {
		if (TextUtils.isEmpty(replace)) {
			return base.getSuperNumber();
		}
		if (base.getType() == ContactsBaseBean.TYPE_PERSONAL) {
			return Html.fromHtml(text.replace(replace,
					"<font color=\"#FFBD42\">" + replace + "</font>"));
		} else {
			try {
			return Html.fromHtml(text.replace(replace,
					"<font color=\"#FFBD42\">" + replace + "</font>"));
			} catch(NullPointerException e) {
				if(text != null) {
					return text;
				} else {
					return "";
				}
			}
		}

	}

	public static CharSequence replaceTextColor(String text, String replace) {
		if (TextUtils.isEmpty(replace)) {
			return text;
		}
		return Html.fromHtml(text.replace(replace, "<font color=\"#FFBD42\">"
				+ replace + "</font>"));
	}
}
